By
    
      yusijia
    
  
    
    Updated:
    
  
	
		
		
		
		
		一.缓冲输入文件
  如果想要打开一个文件用于字符输入,可以使用以String或File对象作为文件名的FileInputReader。为了提高速度,我们希望对那个文件进行缓冲,那么我么将所产生的引用传给一个BufferedReader构造器,由于BufferedReader也提供readLine()方法,所以这是我们的最终对象和进行读取的接口。当readLine()将返回null时,你就达到了文件结尾。

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
   |  public static String Bread(String filename) throws IOException{ 		BufferedReader in = new BufferedReader(new FileReader(filename)); 		String s; 		StringBuilder sb = new StringBuilder(); 		while((s = in.readLine()) != null) 			sb.append(s + "\n"); 		in.close(); 		return sb.toString(); 	} 	 	 	public static void main(String args[]) throws IOException { 		System.out.print(Bread("K:\\rot\\fileTwo.java")); 	}
 
  | 
 
字符串sb用来累积文件的全部内容(包括添加的换行符,因为readLine()已经将他们删掉)。最后调用close()关闭文件。
二、基本的文件输出
- FileWriter 用于写入字符流。要写入原始字节流,请考虑使用 FileOutputStream。 
 
- FileReader 用于以字符为单位读取文本文件
 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
   |  public static void main(String args[]) throws IOException { 		 		BufferedReader br = new BufferedReader(new FileReader("K:\\rot\\fileTwo.java")); 		try{ 			String str = null; 			while((str = br.readLine()) != null) 				System.out.println(str); 		} 		catch(IOException e){ 			e.printStackTrace(); 		} 		finally{ 			br.close(); 		}
  	}
 
  | 
 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
   |  public static void main(String args[]) throws IOException { 	BufferedReader br = new BufferedReader(new FileReader("K:\\rot\\fileTwo.java")); 	BufferedWriter bw = new BufferedWriter(new FileWriter("K:\\rot\\output.txt")); 	try{ 		String str = null; 		while((str = br.readLine()) != null){ 			bw.write(str); 			bw.newLine(); 		} 	}catch(IOException e){ 		e.printStackTrace(); 	} 	finally{ 		br.close(); 		bw.close(); 	} 	}
 
  |